package com.leha.forum.lehare.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leha.forum.lehare.entity.Permission;
import com.leha.forum.lehare.entity.Role;
import com.leha.forum.lehare.service.PermissionService;
import com.leha.forum.lehare.mapper.PermissionMapper;
import com.leha.forum.lehare.service.RolePermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
* @author Administrator
* @description 针对表【permission】的数据库操作Service实现
* @createDate 2025-04-15 21:44:28
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
    implements PermissionService{
    @Resource
    private RolePermissionService rolePermissionService;

    @Transactional
    @Override
    public boolean deletePermission(Integer permissionId) {
        if (permissionId <= 0) {
            throw new IllegalArgumentException("权限 ID 无效");
        }

        if (rolePermissionService.deleteByPermissionId(permissionId) && removeById(permissionId)) {
            return true;
        } else {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public boolean saveOrUpdatePermission(Permission permission) {
        if (permission.getPermissionId() != null && permission.getPermissionId() > 0) {
            Permission existing = getById(permission.getPermissionId());
            if (existing != null) {
                return updateById(permission);
            } else {
                throw new IllegalStateException("权限 " + permission.getPermissionId() + " 不存在");
            }
        } else {
            permission.setPermissionId(null);
            return save(permission);
        }
    }
}




